<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\Storage;

class Resource extends BaseModel
{
    protected $table = 'sys_resource';

    protected $appends = ['imgSrv'];

    protected $visible = ["id","path","imgSrv"];

    public function getImgSrvAttribute()
    {
        if(preg_match('/image/i',$this->type)) {
            if($this->uploadType == "local") {
                return asset('storage/'.$this->path);
            }elseif ($this->uploadType == "qiniu"){
                return $this->getQiniuImageSrv();
            }else{
                return $this->path;
            }
        }

        if ($this->uploadType == "qiniu") {
            return $this->getQiniuImageSrv();
        }
    }

    private function getQiniuImageSrv()
    {
        if($domain = env('QINIU_DOMAINS_CUSTOM')) {
            return $domain.'/'.$this->path;
        }
        if($domain = env('QINIU_DOMAINS_HTTPS')) {
            return $domain.'/'.$this->path;
        }
        if($domain = env('QINIU_DOMAINS_DEFAULT')) {
            return $domain.'/'.$this->path;
        }
        return $this->path;

    }

    public static function saveUploadFile($file,$uploadType="qiniu")
    {
        $ext = $file->getClientOriginalExtension();
        $type = $file->getMimeType();


        if($uploadType == "local") {
            $path = $file->store('public/upload/'.date('Ymd'));
            $path = str_replace('public/','',$path);
        }elseif($uploadType == "qiniu"){

            $dir = explode("/",$type);
            $dir = (isset($dir[0]) && $dir[0])?$dir[0]:'default';

            $path = 'dadu/'.$dir.'/'.date('Ymd') .'/'.str_random(64).'.'.$ext;

            $disk = Storage::disk('qiniu');
            $disk->put($path,file_get_contents($file->path()));
        }else{
            return false;
        }

        $m = new Resource();
        $m->name = $file->getClientOriginalName();
        $m->uploadType = $uploadType;
        $m->type = $type;
        $m->size = $file->getSize();
        $m->path = $path;
        $m->save();

        return $m;
    }
}
